/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package service.token;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import common.Constants;
import common.HttpsUtil;
import entity.menu.AccessToken;
import lombok.extern.log4j.Log4j;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import service.https.HttpsService;

/**
 * @author Mht
 * @date May 31, 2016
 */
@Log4j
@Service
public class TokenService {

	@Resource
	private HttpsService httpsService;

	private final static String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	public AccessToken queryAccessToken(String appid, String secret) {
		AccessToken token = null;
		String requestUrl = tokenUrl.replace("APPID", appid).replace("APPSECRET", secret);
		JSONObject object = httpsService.httpRequest(requestUrl, Constants.HTTP_GET, null);
		if (null != object) {
			try {
				token = new AccessToken();
				token.setToken(object.getString("access_token"));
				token.setExpiresIn(object.getInt("expires_in"));
			} catch (JSONException e) {
				token = null;
				log.error(String.format("获取Token失败 -- ErrorCode : {%n} ErrorMsg : {%s}",
						object.getInt(Constants.ERROR_CODE), object.getString(Constants.ERROR_MSG)));
			}
		}
		return token;
	}

	public AccessToken queryAccessTokenWithStatic(String appid, String secret) {
		AccessToken token = null;
		String requestUrl = tokenUrl.replace("APPID", appid).replace("APPSECRET", secret);
		JSONObject object = HttpsUtil.httpRequest(requestUrl, Constants.HTTP_GET, null);
		if (null != object) {
			try {
				token = new AccessToken();
				token.setToken(object.getString("access_token"));
				token.setExpiresIn(object.getInt("expires_in"));
			} catch (JSONException e) {
				token = null;
				log.error(String.format("获取Token失败 -- ErrorCode : {%n} ErrorMsg : {%s}",
						object.getInt(Constants.ERROR_CODE), object.getString(Constants.ERROR_MSG)));
			}
		}
		return token;
	}
	
}
